<template>
  <div id="app">
    <h1>todolist</h1>
    <div class="box">
      <input
        type="text"
        class="input"
        placeholder="输入待办项"
        v-model="msg"
        @keyup.enter="handleEnter(msg)"
      />
      <div v-if="incomplete.length" class="incomplete">
        <h3>未完成--{{ incomplete.length }}</h3>
        <ul v-for="(item, index) of incomplete" :key="item">
          <li>
            <input type="checkbox" @click="handleClick(index, 'incomplete')" />
            {{ item }}
            <button @click="handleDe(index, 'incomplete')">删除</button>
          </li>
        </ul>
      </div>
      <div v-if="complete.length" class="complete">
        <h3>已完成--{{ complete.length }}</h3>
        <ul v-for="(item, index) of complete" :key="item">
          <li>
            <input type="checkbox" @click="handleClick(index)" checked />
            {{ item }}
            <button @click="handleDe(index)">删除</button>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      msg: "",
      incomplete: [],
      complete: [],
    };
  },
  methods: {
    handleEnter(msg) {
      var incomplete = this.incomplete;
      var complete = this.complete;
      if ((!incomplete.includes(msg))&&(!complete.includes(msg))) {
        incomplete.push(this.msg);
        this.msg = "";
        console.log(this.incomplete);
        localStorage.setItem("incomplete", JSON.stringify(incomplete));
      } else {
        alert("已经在行程中了");
        this.msg = "";
      }
    },
    handleClick(index, val) {
      var incomplete = this.incomplete;
      var complete = this.complete;
      if (val) {
        complete.push(...incomplete.splice(index, 1));
      } else {
        incomplete.push(...complete.splice(index, 1));
      }
      localStorage.setItem("incomplete", JSON.stringify(incomplete));
      localStorage.setItem("complete", JSON.stringify(complete));
    },

    handleDe(index, val) {
      var incomplete = this.incomplete;
      var complete = this.complete;
      if (val) {
        incomplete.splice(index, 1);
        localStorage.setItem("incomplete", JSON.stringify(incomplete));
      } else {
        complete.splice(index, 1);
        localStorage.setItem("complete", JSON.stringify(complete));
      }
    }
  },
  mounted() {
    var incomplete = localStorage.getItem("incomplete");
    var complete = localStorage.getItem("complete");
    if (incomplete) {
      this.incomplete = JSON.parse(incomplete);
    }
    if (complete) {
      this.complete = JSON.parse(complete);
    }
  },
};
</script>

<style scoped>
ul {
  list-style: none;
  margin-left:-50px;
}
li {
  position: relative;
}
button {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
</style>
